#include "util/tool.h"

#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"

static void setMultiSinks()
{
#ifdef QT_DEBUG
    auto log_level = spdlog::level::trace;
#else
    auto log_level = spdlog::level::info;
#endif
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_sink->set_level(log_level);
    console_sink->set_pattern("%^[%H:%M:%S.%e %l] [thread %t] %v%$");

    // 替换 basic_file_sink_mt，文件大  // 小为 10MB，一共保留 3 个日志文件
    //        auto file_sink =
    //        std::make_shared<spdlog::sinks::basic_file_sink_mt>("applet.log",
    //        true);
#ifdef QT_DEBUG
    std::string logpath = "applet.log";
#else
    auto path = nas::utils::pathJoin(nas::utils::getLogLocation(), "applet.log");
    auto logpath = path.toStdString();
#endif
    auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(logpath, 1024 * 1204 * 10, 3);

    file_sink->set_level(log_level);
    file_sink->set_pattern("[%Y-%m-%d %H:%M:%S.%f %l] [thread %t] %v");
    auto logger = std::shared_ptr<spdlog::logger>(new spdlog::logger("multi_sink", {file_sink, console_sink}));
    logger->set_level(log_level);
    spdlog::set_default_logger(logger);
    spdlog::flush_on(log_level);
}

static void message_handler(QtMsgType type, const QMessageLogContext& context, const QString& str)
{
    auto fileName = NetFileTransfer::getBaseName(context.file);
    switch (type)
    {
    case QtMsgType::QtInfoMsg:
        spdlog::info("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
        break;
    case QtMsgType::QtDebugMsg:
        spdlog::debug("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
        break;
    case QtMsgType::QtWarningMsg:
        {
            spdlog::warn("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
            break;
        }
    case QtMsgType::QtCriticalMsg:
        spdlog::critical("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
        break;
    case QtMsgType::QtFatalMsg:
        spdlog::error("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
    // Under VisualStudio, this must be called before main finishes to
    // work around a known VS issue
        spdlog::drop_all();
        break;
    default:
        spdlog::trace("{} +{}: {}", fileName.toStdString(), context.line, str.toStdString());
        break;
    }
}

void initLog()
{
    setMultiSinks();
    qInstallMessageHandler(message_handler);
}
